package com.ding.common;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//延时获取通道,该通道使用延时的策略创建Socket
public class DelayedStreamChannel extends StreamChannel{

    private CreateSocketStrategy createSocketStrategy;

    private OutputStream defaultOutputStream = System.out;

    private InputStream defaultInputStream = new InputStream() {
        @Override
        public int read() throws IOException {
            return -1;
        }
    };

    public InputStream getDefaultInputStream() {
        return defaultInputStream;
    }

    public OutputStream getDefaultOutputStream() {
        return defaultOutputStream;
    }

    //必须有一个创建Socket的策略
    public DelayedStreamChannel(CreateSocketStrategy createSocketStrategy) {
        this.createSocketStrategy = createSocketStrategy;
    }

    public CreateSocketStrategy getCreateSocketStrategy() {
        return createSocketStrategy;
    }

    @Override
    public InputStream getInputStream() {//覆盖输入输出流的获取方式
        if (getSocket()==null) {
            Socket socket = createSocketStrategy.create();
            if (socket == null) {
                return defaultInputStream;
            }
            super.setSocket(socket);
            return super.getInputStream();
        } else {
            return super.getInputStream();
        }
    }

    @Override
    public OutputStream getOutputStream() {
        if (getSocket() == null) {
            Socket socket = createSocketStrategy.create();
            if (socket == null) {
                return defaultOutputStream;
            }
            super.setSocket(socket);
            return super.getOutputStream();
        } else {
            return super.getOutputStream();
        }
    }

}
